//
//  ShoppingViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-10-12.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "ShoppingViewController.h"
#import "CellFactory.h"
#import "PersonalViewController.h"
#import "DynamicDetailViewController.h"
#import "JSONRequest.h"
#import "Helper.h"
#import "JMFBase.h"
#import "MJRefresh.h"

@interface ShoppingViewController ()<DynamicOperateDelegate,JSONRequestDelegate,MJRefreshBaseViewDelegate>
{
    NSMutableArray*                 _messageArray;                  //圈子动态的数据源
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}
@end

@implementation ShoppingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    self.tableView.backgroundView = nil;
    
    //导航栏左按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    _messageArray = [NSMutableArray new];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return _messageArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //获取一条动态信息
    NSDictionary* dynamic = [_messageArray objectAtIndex:indexPath.section];
    
#warning: 这里要优化，使用静态的形式
    NSArray* Cellidentifiers = [NSArray arrayWithObjects:@"Cell_Info", @"Cell_Mood", @"Cell_Goods", @"Cell_Recommend", nil];
    UITableViewCell *cell;
    
    if (indexPath.row == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:[Cellidentifiers objectAtIndex:0]];
        if (cell == nil) {
            //获取复用对象
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[Cellidentifiers objectAtIndex:0]];
            [CellFactory makeCell:cell forName:NamedCellPersonInformation];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.backgroundColor = [UIColor whiteColor];
            cell.backgroundView.backgroundColor = [UIColor whiteColor];
        }
        
        [CellFactory drawCell:cell forName:NamedCellPersonInformation withDictionary:dynamic];
    }
    
    else {
        NSInteger type = [[dynamic objectForKey:@"type"] integerValue];
        NSInteger cellType = type;
        //使用Light类，使界面变得短一些
        if (type == DynamicCategoryProduct) {
            type = 6;
        }
        else if (type == DynamicCategoryRecommend) {
            type = 7;
        }
        else if (type == DynamicCategoryMood) {
            type = 5;
        }
        
        //根据不同的动态类型，获取队列中的不同复用对象
        cell = [tableView dequeueReusableCellWithIdentifier:[Cellidentifiers objectAtIndex:cellType]];
        if (cell == nil) {
            
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[Cellidentifiers objectAtIndex:cellType]];
            [CellFactory makeCell:cell forName:type];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.backgroundColor = [UIColor whiteColor];
            cell.backgroundView.backgroundColor = [UIColor whiteColor];
        }
        
        [CellFactory drawCell:cell forName:type withDictionary:dynamic];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 2.5f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 2.5f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 0.0f;
    
    NSDictionary *dynamic = [_messageArray objectAtIndex:indexPath.section];
    
    if (indexPath.row == 1) {
        
        NSInteger type = [[dynamic objectForKey:@"type"] intValue];
        //如果type是产品/推荐信息就是用Light类，使界面变得短一些
        if (type == DynamicCategoryProduct) {
            type = 6;
        }
        else if (type == DynamicCategoryRecommend) {
            type = 7;
        }
        else if (type == DynamicCategoryMood) {
            type = 5;
        }
        height = [CellFactory heightForName:type withDictionary:dynamic];
    }
    else {
        height = [CellFactory heightForName:NamedCellPersonInformation withDictionary:dynamic];
    }
    
    return height;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //获得被用户选中的动态
    NSDictionary *dynamicIsSelected = [_messageArray objectAtIndex:[indexPath section]];
    
    //如果用户点击的是个人简洁信息栏，那么就跳转到动态发起人的个人信息页面
    if (indexPath.row == 0) {
        
        //获取动态发起人的personid
        NSInteger psersonId = [[dynamicIsSelected objectForKey:@"creatorId"] integerValue];
        
        //跳转到个人信息页面
        PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:psersonId and:dynamicIsSelected[@"appKey"]];
        personalInfoVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:personalInfoVC animated:YES];
        
    }else{
        
        NSInteger dynamicId = [[dynamicIsSelected objectForKey:@"id"] integerValue];
        
        DynamicDetailViewController *trendDetailVC = [[DynamicDetailViewController alloc] initWithID:dynamicId];
        trendDetailVC.hidesBottomBarWhenPushed = YES;
        trendDetailVC.operateDelegate = self;
        [self.navigationController pushViewController:trendDetailVC animated:YES];
    }
    
}

#pragma mark - 私有方法

/*!
 @abstract 通过checkid查询向服务器请求更多的动态
 @param checkId 需要分页功能时，传入此id，即数据源中最后一条数据的ID
 */
- (void)circleMessageRequestWithCheckId:(NSInteger)checkId
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_SHOPPING_LIST];
    request.delegate = self;
    request.requestMode = RequestModeMultiPart;
    //checkId存在，则表明是加载更多
    if (checkId != 0) {
        
        [request setValue:[NSNumber numberWithInteger:checkId] forParameter:@"checkId"];
        [request setSuccessSelector:@selector(moreCircleMessageDidReceived:)];
    }
    [request asynchronous];
}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (NSInteger)catchTheLastDataSourceId
{
    //获取数据源最后一项对象的id属性
    if (_messageArray.count > 0) {
        return [[[_messageArray objectAtIndex:(_messageArray.count - 1)] objectForKey:@"id"] integerValue];
    }
    return 0;
}

#pragma mark - JSONRequest Delegate
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_messageArray.count != 0) {
            [_messageArray removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_messageArray addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = self.tableView;
        }
        
        if (_messageArray.count > 0) {
            self.tableView.tableFooterView.hidden = NO;
        }
        else {
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
        
//        //当为下拉刷新和初次进入时，应该对数据源进行格式化
//        if (!_isFooterRefresh) {
//            
//            if (_messageArray == nil) {
//                _messageArray = [[NSMutableArray alloc] init];
//                
//            }else{
//                
//                [_messageArray removeAllObjects];
//            }
//            
//            //下拉刷新后将badgevalue清零
//            [self.navigationController.tabBarItem setBadgeValue:nil];
//        }
//        
//        //加载更多后成功获取数据后，应先调用此方法，恢复到点击加载更多之前的页面状态
//        [super stopRefresh];
//        
//        //如果加载更多没有得到数据，那么就提示用户，并且暂时隐藏家在更多
//        //在有数据的情况，就添加到数据源
//        if ([(NSArray *)jmf.data count] == 0) {
//            
//            //如果是加载更多时出现空数据源，那么就提示用户
//            if (_isFooterRefresh) {
//                [Helper showAllTextDialog:_L(@"title_nomore_01") inView:self.view];
//            }
//            
//            self.disableBottomRefresh = YES;
//            
//        }
//        //有数据情况下，对数据进行一次过滤，只显示商品没有下架或没有停售的
//        else{
//            
//            //有数据的时候，加载更多要显示出来
//            self.disableBottomRefresh = NO;
//            
//            NSMutableArray* filteredUnsaleProducts = [[NSMutableArray alloc] init];
//            for (NSDictionary* dynamic in jmf.data) {
//                
//                //如果产品状态正常，没有停售或下架，就保存
//                if (([dynamic[@"product"][@"status"] intValue] == 0)) {
//                    
//                    [filteredUnsaleProducts addObject:dynamic];
//                }
//            }
//            
//            //将保存好的数组载入
//            [_messageArray addObjectsFromArray:filteredUnsaleProducts];
//        }
//        [self.tableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
//    //设置成刷新模式为默认下拉刷新
//    _isFooterRefresh = NO;
    
}

- (void)moreCircleMessageDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            self.tableView.tableFooterView.hidden = NO;
            [_messageArray addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        else{
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - 自定义事件

- (void)backButtonEvent
{
    [self.navigationController popViewControllerAnimated:true];
}

///*!
// @abstract 加载更多button被点击
// */
//- (void)refreshButtonEvent:(id)sender
//{
//    
//    [super refreshButtonEvent:sender];
//    
//    //如果原数据源为空，就没必要加载更多
//    if (_messageArray.count == 0) {
//        
//        [Helper showAllTextDialog:_L(@"title_nomore_01") inView:self.view];
//        
//        //设置成刷新模式为默认下拉刷新
//        _isFooterRefresh = NO;
//        //        self.disableBottomRefresh = YES;
//        
//        return;
//    }
//    
//    //发送加载更多的请求,数据接受成功后，设置_reloading
//    [self circleMessageRequestWithCheckId:[self catchTheLastDataSourceId]];
//}

//#pragma mark -
//#pragma mark Data Source Loading / Reloading Methods
//
//- (void)reloadTableViewDataSource{
//	
//	[super reloadTableViewDataSource];
//    
//    [self circleMessageRequestWithCheckId:nil];
//    
//}

#pragma mark - DynamicOperateDelegate

//
- (void)dynamic:(NSDictionary *)dynamic operate:(int)flag
{
    if (flag == 3) {
        [_messageArray removeObject:dynamic];
        [self.tableView reloadData];
    }
    else if (flag == 2) {
        for (int i = 0; i < _messageArray.count; i++) {
            
            NSDictionary* d = [_messageArray objectAtIndex:i];
            
            if ([d[@"id"] integerValue] == [dynamic[@"id"] integerValue]) {
                
                [_messageArray replaceObjectAtIndex:i withObject:dynamic];
                [self.tableView reloadData];
                break;
            }
        }
    }
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self circleMessageRequestWithCheckId:0];
    }
    
    //上拉加载更多
    else {
        
        [self circleMessageRequestWithCheckId:[self catchTheLastDataSourceId]];
        
    }
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}
@end
